<?php
/**
 * Download.php
 * User: tommy
 */

namespace app\admin\controller;

use Svick\Core\Request;
use Svick\File\File;

class Download
{
    /**
     * 下载excel
     *
     * @return string|null
     */
    public function excel()
    {
        set_time_limit(0);

        $unionid = Request::getString('unionid');
        $json_file = ROOT_PATH . 'tmp/excel/' . $unionid . '.json';
        if (!file_exists($json_file)) {
            return '要下载的文件不存在';
        }
        $data = file_get_contents($json_file);
        $data = json_decode($data, true);
        $name = $data['name'];

        $filename = $name . date('Y-m-d-His') . '.xlsx';
        $filepath = File::formatPath(ROOT_PATH . 'tmp/excel/' . $unionid . '.xlsx');
        if (!file_exists($filepath)) {
            return '要下载的文件不存在';
        }

        // Set Header
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Cache-Control: max-age=0');
        header('Pragma: public');

        readfile($filepath);
        flush();

        // Delete temporary file
        @unlink($filepath);
        @unlink($json_file);

        return null;
    }
}
